let _Vue = null

export default class VueRouter {
  static install (Vue) {
    // 判断当前插件是够已经被安装
    if (VueRouter.install.installed) return
    VueRouter.install.installed = true
    // 把Vue构造函数记录到全局变量
    _Vue = Vue
    // 把创建Vue实例时候传入的router对象注入到Vue实例上
    _Vue.mixin({
      beforeCreate () {
        // 判断this.$options.router，组件没有此属性
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router
          this.$options.router.init(_Vue)
        }
      },
    })
  }

  constructor (options) {
    this.options = options
    this.mode = options.mode
    // 判断mode的值是否正确
    if (this.mode !== 'history' && this.mode !== 'hash') throw new Error('vueRouter mode must be hash or history')
    this.routeMap = {}
    // 根据mode的值设置对应的current参数
    this.data = this.setRouterData(this.mode)
  }

  setRouterData (mode) {
    const { pathname, hash } = window.location
    return _Vue.observable({
      current: mode === 'history' ? pathname : hash.substr(1)
    })
  }

  init (Vue) {
    this.initRouteMap()
    this.initComponents(Vue)
    this.initEvent()
  }

  initRouteMap () {
    // 遍历所有的路由规则，把路由规则解析成键值对的形式存储到routeMap中
    this.options.routes.forEach(route => {
      this.routeMap[route.path] = route.component
    })
  }

  initComponents (Vue) {
    const self = this
    const { mode } = self
    
    Vue.component('router-link', {
      props: {
        to: String,
      },
      // 此处用template时，如果Vue时运行时版将会报错，因为运行时版没有编译器，无法编译模板
      // template: '<a :href="to"><slot></slot></a>'
      // 使用render函数代替template
      render (h) {
        return h('a', {
          attrs: {
            href: mode === 'history' ? this.to : `#${this.to}`,
          },
          on: {
            click: this.handleClick,
          },
        }, [this.$slots.default])
      },
      methods: {
        handleClick (e) {
          if (mode === 'history') {
            history.pushState({}, '', this.to)
            e.preventDefault()
          } else {
            window.location.hash = `#${this.to}`
          }
          this.$router.data.current = this.to
        },
      },
    })

    Vue.component('router-view', {
      render (h) {
        const component = self.routeMap[self.data.current]
        return h(component)
      },
    })
  }

  initEvent () {
    const { mode } = this
    const eventName = mode === 'history' ? 'popstate' : 'hashchange'
    window.addEventListener(eventName, () => {
      const { pathname, hash } = window.location
      const currentPath = mode === 'history' ? pathname : hash.substr(1)
      this.data.current = currentPath
    })
  }
}